#ifndef __LIST_H_
#define __LIST_H_
#include <types.h>


#define LIST_HEAD_INIT(name)    {&(name), &(name)}

#define LIST_HEAD(name) \
            struct list_head name = LIST_HEAD_INIT(name)
/**
 * 
 * 遍历每一个list_head 节点
 */
#define list_for_each(pos, head) \
    for  (pos = (head)->next; pos != (head); pos = pos->next)
/**
 * 获得结构体的地址
 * 
 */
#define list_entry(member, type, ptr) \
    container_of(member, type, ptr)
/**
 * 获得包含ptr->next的
 * 结构体首地址
 */
#define list_first_entry(member, type, ptr) \
    list_entry(member, type, (ptr)->next)
/**
 * 通过结构体获取
 * 下一个结构体地址
 */
#define list_next_entry(member, pos) \
    list_entry(member, typeof(*pos), (pos)->member.next)
/**
 * list_for_each_entry
 * 
 */
#define list_for_each_entry(member, head, pos) \
    for (pos = list_first_entry(member, typeof(*pos), head)); \
         &pos->member != (head); \
         pos = list_next_entry(member, pos)

/*   list双向链表   */
struct list_head {
    struct list_head *pre, *next;
};
/**
 * @brief list_init
 * 初始化
 * @param pnode 
 * @return STATIC_INLINE 
 */
STATIC_INLINE void list_init(struct list_head *pnode)
{
    pnode->next = pnode->pre = pnode;
}
static inline void __list_add(struct list_head *new,
                    struct list_head *pre,
                    struct list_head *next)
{
    next->pre = new;
    new->next = next;
    new->pre = pre;
    pre->next = new;
    // printk("pre:%x,%x\n new:%x,%x \n next:%x, %x\n",pre->pre,pre->next
    //                                                 ,new->pre,new->next
    //                                                 ,next->pre,next->next);
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->pre, head);
}

/*   删除两个节点中间的节点   */
static inline void __list_del(struct list_head *pre, struct list_head *next)
{
    next->pre = pre;
    pre->next = next;
}

#define NON_NULL_P  (void*)0x100
static inline void __list_del_entry(struct list_head *entry)
{
    __list_del(entry->pre, entry->next);
    entry->next = entry->pre = NON_NULL_P;
}

static inline void list_replace(struct list_head *old, struct list_head *new)
{
    new->next = old->next;
    new->next->pre = new;
    new->pre = old->pre;
    new->pre->next = new;
}

static inline int list_empty(struct list_head *head)
{
    return head->next = head->pre;
}

#define foreach_llist(node, head)   for(node = head; node != NULL; node = node->next)

#endif